﻿/*-------------------------------------------------------------------------
* 命名空间: WaferSelectV3.ViewModels/ResultSummaryViewModel
* 类       名: ResultSummaryViewModel
* 功      能:  TD
* 时      间:  2024-04-29 17:46:18
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using Microsoft.IdentityModel.Logging;
using Microsoft.Win32;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using SiliconSelect.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WaferSelectV3.Common;
using WaferSelectV3.DAL.DataEntity;
using WaferSelectV3.DAL.LocalDataAccess;
using WaferSelectV3.Models;
using WaferSelectV3.Services;

namespace WaferSelectV3.ViewModels
{
    public class ResultSummaryViewModel : BindableBase, INavigationAware
    {

        private bool _isRefresh;

        public bool IsRefresh
        {
            get { return _isRefresh; }
            set
            {
                _isRefresh = value;
                RaisePropertyChanged();
            }
        }

        private string? _searchValue;

        public string? SearchValue
        {
            get { return _searchValue; }
            set
            {
                _searchValue = value;
                RaisePropertyChanged();
            }
        }

        public ResultSummaryViewModel()
        {
            PageOperaterCommand = new DelegateCommand<string>(DoPageOperater);
            DataOperateCommand = new DelegateCommand<string>(DoDataOperate);
            SearchTypeList = new ObservableCollection<string>()
            {
                "晶棒编号",
                "汇总等级",
                "等级类型",
                "类型描述"
            };
        }

        public string? SearchCrystalName = string.Empty;

        private string? _exportDir;
        /// <summary>
        /// 汇总导出目录
        /// </summary>
        public string? ExportDir
        {
            get { return _exportDir; }
            set
            {
                _exportDir = value;
                RaisePropertyChanged();
            }
        }


        /// <summary>
        /// 数据查询操作按钮
        /// </summary>
        public DelegateCommand<string> DataOperateCommand { get; private set; }
        private void DoDataOperate(string commandParameter)
        {
            if (!string.IsNullOrWhiteSpace(commandParameter))
            {
                switch (commandParameter)
                {
                    case "Query":
                        if (SearchTypeSelectedIndex == 0)
                        {
                            var searchResult = WaferSummaryAccess.GetTotalResultSummaryTableNames();
                            if (!searchResult.State)
                            {
                                LoggerHelper.WriteLogMain(searchResult.Message!, LogType.Fatal);
                                MessageBox.Show(searchResult.Message, "数据库操作失败", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            var searchTableName = WaferSummaryAccess.GetTableNameByCrystalNumber(SearchValue!);
                            if (!searchResult.Data!.Contains(searchTableName))
                            {
                                MessageBox.Show($"你要查询的晶棒编号_{SearchValue}不存在,请重新输入!", "晶棒编号输入错误", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            var resultSummary = WaferSummaryAccess.GetResultSummaryByCrystalName(SearchValue!);
                            if (!resultSummary.State)
                            {
                                LoggerHelper.WriteLogMain(resultSummary.Message!, LogType.Fatal);
                                MessageBox.Show(resultSummary.Message, "数据库操作失败", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                            SearchCrystalName = SearchValue;
                            UpdateModelFromEntity(resultSummary.Data);
                        }
                        else
                        {
                            var resultSummary = WaferSummaryAccess.GetResultSummaryByCrystalName(SearchCrystalName!);
                            if (!resultSummary.State)
                            {
                                LoggerHelper.WriteLogMain(resultSummary.Message!, LogType.Fatal);
                                MessageBox.Show(resultSummary.Message, "数据库操作失败", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                            if (resultSummary.Data == null || resultSummary.Data.Count == 0)
                            {
                                return;
                            }
                            List<WaferSummaryEntity> searchRes = new List<WaferSummaryEntity>();
                            if (SearchTypeSelectedIndex == 1)
                            {
                                searchRes = resultSummary.Data!.Where(x => x.DetectedLevel == SearchValue).ToList();
                            }
                            else if (SearchTypeSelectedIndex == 2)
                            {
                                searchRes = resultSummary.Data!.Where(x => x.LevelType == SearchValue).ToList();
                            }
                            else
                            {
                                searchRes = resultSummary.Data!.Where(x => x.TypeDescription == SearchValue).ToList();
                            }
                            UpdateModelFromEntity(searchRes);
                        }
                        break;
                    case "Export":
                        // 导出数据
                        if (ResultSummaryTotal?.Count == 0)
                        {
                            MessageBox.Show("要导出的数据为空,请先查询对应数据再导出", "数据导出错误提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                        // 根据搜索的选项,如果不是第一个,按照晶棒编号,就要将结果加上查询值的后缀
                        string exportDir = PathDirProvider.SummaryExportDir;
                        string exportFileName = SearchCrystalName!;
                        if (SearchTypeSelectedIndex != 0)
                        {
                            exportFileName += $"_{SearchValue}";
                        }
                        SaveFileDialog dialog = new SaveFileDialog();
                        dialog.Title = "导出路径";
                        dialog.Filter = "文档|*.csv;*.xls;*.xlsx";
                        dialog.CheckFileExists = false;
                        dialog.RestoreDirectory = true;
                        dialog.InitialDirectory = exportDir;
                        dialog.FileName = exportFileName;
                        bool? dialogResult = dialog.ShowDialog();
                        if (dialogResult != null && dialogResult == false)
                        {
                            return;
                        }
                        ExportDir = Path.GetDirectoryName(dialog.FileName);
                        exportFileName = Path.GetFileName(dialog.FileName);
                        Task.Run(() =>
                        {
                            DataResult saveResult = WaferSummaryAccess.SaveSummaryListToCsv(Path.Combine(exportDir, exportFileName), ResultSummaryTotal, false);

                        });
                        break;
                }
            }

        }


        private void DoPageOperater(string commandParameter)
        {
            if (!string.IsNullOrWhiteSpace(commandParameter))
            {
                switch (commandParameter)
                {
                    case "PrePage":
                        // 上一页
                        if (CurrentPage <= 1) return;
                        else
                        {
                            ResultSummaryPage!.Clear();
                            for (int i = (CurrentPage - 2) * _singlePageCount; i < _singlePageCount + (CurrentPage - 2) * _singlePageCount; i++)
                            {
                                ResultSummaryPage.Add(ResultSummaryTotal![i]);
                            }
                            CurrentPage--;
                            CurrentPageCount = ResultSummaryPage.Count;
                        }
                        break;
                    case "NextPage":
                        // 下一页
                        if (CurrentPage >= TotalPage) return;
                        else
                        {
                            ResultSummaryPage?.Clear();
                            int finalCountMax = Math.Min(CurrentPage * _singlePageCount + _singlePageCount, ResultSummaryTotal!.Count);
                            for (int i = CurrentPage * _singlePageCount; i < finalCountMax; i++)
                            {
                                ResultSummaryPage!.Add(ResultSummaryTotal[i]);
                            }
                            CurrentPage++;
                            CurrentPageCount = ResultSummaryPage!.Count;
                        }
                        break;
                    case "GoForward":
                        // 跳转指定页面
                        int number;
                        bool res = int.TryParse(CurrentPageShow, out number);
                        if (res)
                        {
                            // 如果成功了
                            if (number > TotalPage)
                            {
                                CurrentPage = TotalPage;
                            }
                            else if (number <= 1)
                            {
                                CurrentPage = 1;
                            }
                            else
                            {
                                CurrentPage = number;
                            }

                            ResultSummaryPage!.Clear();
                            int finalCountMax = Math.Min((CurrentPage - 1) * _singlePageCount + _singlePageCount, ResultSummaryTotal!.Count);

                            for (int i = (CurrentPage - 1) * _singlePageCount; i < finalCountMax; i++)
                            {
                                ResultSummaryPage.Add(ResultSummaryTotal![i]);
                            }
                            CurrentPageCount = ResultSummaryPage.Count;

                        }
                        else
                        {
                            MessageBox.Show("输入格式错误,请输入正确的数字!", "数据输入格式错误提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        public DelegateCommand<string> PageOperaterCommand { get; private set; }

        /// <summary>
        /// 一页显示的数据个数
        /// </summary>
        private int _singlePageCount = 1000;
        /// <summary>
        /// 汇总结果表所有的结果
        /// </summary>
        public List<WaferSummaryModel>? ResultSummaryTotal;

        /// <summary>
        /// 汇总结果当前页面要显示的结果
        /// </summary>
        private ObservableCollection<WaferSummaryModel>? _resultSummaryPage;

        public ObservableCollection<WaferSummaryModel>? ResultSummaryPage
        {
            get { return _resultSummaryPage; }
            set
            {
                _resultSummaryPage = value;
                RaisePropertyChanged();
            }
        }

        private int _currentPage;

        public int CurrentPage
        {
            get { return _currentPage; }
            set
            {
                CurrentPageShow = $"{value} / {TotalPage}";
                _currentPage = value;
                RaisePropertyChanged();
            }
        }

        private int _totalPage;

        public int TotalPage
        {
            get { return _totalPage; }
            set
            {
                _totalPage = value;
                RaisePropertyChanged();
            }
        }


        private int _currentPageCount;

        public int CurrentPageCount
        {
            get { return _currentPageCount; }
            set
            {
                _currentPageCount = value;
                RaisePropertyChanged();
            }
        }

        private int _totalPageCount;

        public int TotalPageCount
        {
            get { return _totalPageCount; }
            set
            {
                _totalPageCount = value;
                RaisePropertyChanged();
            }
        }

        private string? _currentPageShow;

        public string? CurrentPageShow
        {
            get { return _currentPageShow; }
            set
            {
                _currentPageShow = value;
                RaisePropertyChanged();
            }
        }

        private ObservableCollection<string>? _searchTypeList;

        public ObservableCollection<string>? SearchTypeList
        {
            get { return _searchTypeList; }
            set
            {
                _searchTypeList = value;
                RaisePropertyChanged();
            }
        }

        private int _searchTypeSelectedIndex;

        public int SearchTypeSelectedIndex
        {
            get { return _searchTypeSelectedIndex; }
            set
            {
                _searchTypeSelectedIndex = value;
                switch (value)
                {
                    case 0:
                        SearchValue = GlobalValues.CurrentCrystalName;
                        break;
                    case 1:
                        SearchValue = "31"; break;
                    case 2:
                        SearchValue = "缺数直流"; break;
                    case 3:
                        SearchValue = "缺数直流,缺数据工位";
                        break;
                }
                RaisePropertyChanged();
            }
        }


        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            ResultSummaryPage?.Clear();
            ResultSummaryTotal?.Clear();
            ResultSummaryTotal = null;
            ResultSummaryPage = null;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            SearchTypeSelectedIndex = 0;
            IsRefresh = true;
            ResultSummaryTotal = new List<WaferSummaryModel>();
            ResultSummaryPage = new ObservableCollection<WaferSummaryModel>();
            SearchCrystalName = GlobalValues.CurrentCrystalName;
            ExportDir = PathDirProvider.SummaryExportDir;
            Task.Run(() =>
            {
                ReloadSummary();
            });
        }

        private void ReloadSummary()
        {
            var resultSummary = WaferSummaryAccess.GetResultSummaryByCrystalName(GlobalValues.CurrentCrystalName);
            if (!resultSummary.State)
            {
                LoggerHelper.WriteLogMain(resultSummary.Message!, LogType.Fatal);
                MessageBox.Show(resultSummary.Message, "数据库操作失败", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            UpdateModelFromEntity(resultSummary.Data);
        }

        private void UpdateModelFromEntity(List<WaferSummaryEntity>? dataEntities)
        {
            Application.Current?.Dispatcher?.Invoke(() =>
            {
                ResultSummaryTotal?.Clear();
                ResultSummaryPage?.Clear();
            });

            if (dataEntities != null && dataEntities.Count > 0)
            {
                foreach (var result in dataEntities)
                {
                    WaferSummaryModel model = new WaferSummaryModel()
                    {
                        DetectedTime = result.DetectedTime,
                        ProductionDate = result.ProductionDate,
                        WaferId = result.WaferId,
                        CutNumber = result.CutNumber,
                        CrystalNumber = result.CrystalNumber,
                        PositionNumber = result.PositionNumber,
                        ProductionLot = result.ProductionLot,
                        FlowerNumber = result.FlowerNumber,
                        DetectionRecipe = result.DetectionRecipe,
                        DetectedLevel = result.DetectedLevel,
                        LevelType = result.LevelType,
                        TypeDescription = result.TypeDescription,
                        BoxNumber = result.BoxNumber,
                        ThicknessAver = result.ThicknessAver,
                        TTV = result.TTV,
                        LineTraceMax = result.LineTraceMax,
                        Warping = result.Warping,
                        ThicknessMin = result.ThicknessMin,
                        ThicknessMax = result.ThicknessMax,
                        IsDenseLine = result.IsDenseLine,
                        LineTraceUpNum = result.LineTraceUpNum,
                        LineTraceUpMax = result.LineTraceUpMax,
                        LineTraceDownNum = result.LineTraceDownNum,
                        LineTraceDownMax = result.LineTraceDownMax,
                        LineTraceCount = result.LineTraceCount,
                        ResistivityAver = result.ResistivityAver,
                        ResistivityMax = result.ResistivityMax,
                        ResistivityMin = result.ResistivityMin,
                        LengthMax = result.LengthMax,
                        LengthMin = result.LengthMin,
                        LengthX = result.LengthX,
                        LengthY = result.LengthY,
                        DiagonalLeftStart = result.DiagonalLeftStart,
                        DialonalRightStart = result.DialonalRightStart,
                        ChamferMax = result.ChamferMax,
                        ChamferMin = result.ChamferMin,
                        UpDownParallel = result.UpDownParallel,
                        LeftRightParallel = result.LeftRightParallel,
                        SquareLineMax = result.SquareLineMax,
                        SquareLineMin = result.SquareLineMin,
                        VerticalAngleMax = result.VerticalAngleMax,
                        VerticalAngleMin = result.VerticalAngleMin,
                        LeftTopCharmfer = result.LeftTopCharmfer,
                        RightTopCharmfer = result.RightTopCharmfer,
                        LeftBottomCharmfer = result.LeftBottomCharmfer,
                        RightBottomCharmfer = result.RightBottomCharmfer,
                        LeftTopAngle = result.LeftTopAngle,
                        RightTopAngle = result.RightTopAngle,
                        LeftBottomAngle = result.LeftBottomAngle,
                        RightBottomAngle = result.RightBottomAngle,
                        LengthXMax = result.LengthXMax,
                        LengthXMin = result.LengthXMin,
                        LengthYMax = result.LengthYMax,
                        LengthYMin = result.LengthYMin,

                        FrontEdgeBreakExist = result.FrontEdgeBreakExist,
                        FrontEdgeBreakNum = result.FrontEdgeBreakNum,
                        FrontEdgeBreakArea = result.FrontEdgeBreakArea,
                        BackEdgeBreakExist = result.BackEdgeBreakExist,
                        BackEdgeBreakNum = result.BackEdgeBreakNum,
                        BackEdgeBreakArea = result.BackEdgeBreakArea,
                        LeftEdgeBreakExist = result.LeftEdgeBreakExist,
                        LeftEdgeBreakNum = result.LeftEdgeBreakNum,
                        LeftSurfaceBreakNum = result.LeftSurfaceBreakNum,
                        LeftSurfaceBreakExist = result.LeftSurfaceBreakExist,
                        RightEdgeBreakExist = result.RightEdgeBreakExist,
                        RightEdgeBreakNum = result.RightEdgeBreakNum,
                        RightSurfaceBreakExist = result.RightSurfaceBreakExist,
                        RightSurfaceBreakNum = result.RightSurfaceBreakNum,
                        SumdgeUpExist = result.SumdgeUpExist,
                        SmudgeUpArea = result.SmudgeUpArea,
                        SumdgeUpNum = result.SumdgeUpNum,
                        SumdgeUpReverse = result.SumdgeUpReverse,
                        SumdgeUpHoleExist = result.SumdgeUpHoleExist,
                        SumdgeUpHoleNum = result.SumdgeUpHoleNum,
                        HoleExistUp = result.HoleExistUp,
                        HoleNumUp = result.HoleNumUp,
                        SumdgeDownExist = result.SumdgeDownExist,
                        SumdgeDownArea = result.SumdgeDownArea,
                        SumdgeDownNum = result.HoleNumDown,
                        SumdgeDownReverse = result.SumdgeDownReverse,
                        SumdgeDownHoleExist = result.SumdgeDownHoleExist,
                        SumdgeDownHoleNum = result.SumdgeDownHoleNum,
                        HoleExistDown = result.HoleExistDown,
                        HoleNumDown = result.HoleNumDown,
                        SubfissureArea01 = result.SubfissureArea01,
                        SubfissureNum01 = result.SubfissureNum01,
                        SubfissureExist01 = result.SubfissureExist01,
                        SubfissureBreakArea01 = result.SubfissureBreakArea01,
                        SubfissureBreakNum01 = result.SubfissureBreakNum01,
                        SubfissureBreakExist01 = result.SubfissureBreakExist01,
                        SubfissureHoleNum01 = result.SubfissureHoleNum01,
                        SubfissureHoleExist01 = result.SubfissureHoleExist01,
                        SubfissureArea02 = result.SubfissureArea02,
                        SubfissureNum02 = result.SubfissureNum02,
                        SubfissureExist02 = result.SubfissureExist02,
                        SubfissureBreakArea02 = result.SubfissureBreakArea02,
                        SubfissureBreakNum02 = result.SubfissureBreakNum02,
                        SubfissureBreakExist02 = result.SubfissureBreakExist02,
                        SubfissureHoleNum02 = result.SubfissureHoleNum02,
                        SubfissureHoleExist02 = result.SubfissureHoleExist02,
                    };
                    Application.Current?.Dispatcher?.Invoke(() =>
                    {
                        ResultSummaryTotal?.Add(model);
                        if (ResultSummaryTotal?.Count <= _singlePageCount)
                        {
                            ResultSummaryPage?.Add(model);
                        }
                    });
                }

                Application.Current?.Dispatcher?.Invoke(() =>
                {
                    // 每次数据更新的时候,分页信息也要更新一下
                    if (ResultSummaryTotal != null && ResultSummaryPage != null)
                    {
                        TotalPage = ResultSummaryTotal.Count / _singlePageCount + (ResultSummaryTotal.Count % _singlePageCount == 0 ? 0 : 1);
                        CurrentPageCount = ResultSummaryPage!.Count;
                        TotalPageCount = ResultSummaryTotal!.Count;
                        CurrentPage = 1;
                    }
                    //// 如果只有一页
                    //if (TotalPage <= 1)
                    //{
                    //    foreach (var item in ResultSummaryTotal)
                    //    {
                    //        ResultSummaryPage!.Add(item);
                    //    }
                    //}
                    //else
                    //{
                    //    for (int i = 0; i < _singlePageCount; i++)
                    //    {
                    //        ResultSummaryPage!.Add(ResultSummaryTotal[i]);
                    //    }
                    //}

                });
            }
            else
            {
                Application.Current?.Dispatcher?.Invoke(() =>
                {
                    ResultSummaryPage?.Clear();
                    TotalPage = 1;
                    CurrentPage = 1;
                    CurrentPageCount = 0;
                    TotalPageCount = 0;
                });
            }
        }
    }
}
